package com.deloitte.service.rest.jersy;

import java.io.File;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import com.deloitte.model.SlideInfo;
import com.deloitte.util.StringUtilities;

@Path("getslides")
public class SlideInfoService {
	
	private static final Map<String, ArrayList<SlideInfo>>  slideMap = new HashMap<String, ArrayList<SlideInfo>>();
	private static final ArrayList<SlideInfo>  allSlides = new ArrayList<SlideInfo>();
	private static final String rootPath = FileUploadController.getRootPath();
	private static final String indexSeperator = FileUploadController.getIndexSeperator();
	private static MimetypesFileTypeMap mimetypesFileTypeMap;
	private static FileNameMap fileNameMap = URLConnection.getFileNameMap();
	
	public static ArrayList<SlideInfo> getSlides(String catalogCode){
		//load slides if it is empty
		if(slideMap.isEmpty()){
			loadSlides();
		}
		ArrayList<SlideInfo> slides = null;
		if(!StringUtilities.isEmpty(catalogCode)){
			slides = slideMap.get(catalogCode);
		}
		else
		{
			slides = new ArrayList<>();
			slides.addAll(allSlides);
		}
		return slides;
	}
	
	public static void loadSlides(){
		if(mimetypesFileTypeMap == null)
		{
			InputStream is= FileUploadController.class.getClassLoader().getResourceAsStream("mime.types");
			mimetypesFileTypeMap = new MimetypesFileTypeMap(is);
		}
		slideMap.clear();
		//Read all the files in this location
		File file = new File(rootPath);
		if(file.exists() && file.isDirectory()){
			File[] catalogs = file.listFiles();
			if(catalogs != null){
				for(File catalog : catalogs){
					if(catalog != null){
						SlideInfo slideInfo = null;
						if(catalog.isDirectory())
						{
							File[] slides = catalog.listFiles();
							String catalogCode = catalog.getName();
							ArrayList<SlideInfo> slideList = slideMap.get(catalogCode);
							if(slideList == null){
								slideList = new ArrayList<SlideInfo>();
							}
							
							for(File slide : slides)
							{
								slideInfo = getSlideInfo(slide);
								if(slideInfo != null)
								{
									slideInfo.setRootPath(catalogCode);
									slideList.add(slideInfo);
									allSlides.add(slideInfo);
								}
							}
							
							if(!slideList.isEmpty()){
								Collections.sort(slideList);
								slideMap.put(catalogCode, slideList);
							}
						}
						else
						{
							slideInfo = getSlideInfo(catalog);
							if(slideInfo != null)
							{
								allSlides.add(slideInfo);
							}
						}
					}
				}
			}
			
		}
	}
	
	private static SlideInfo getSlideInfo(File slide)
	{
		SlideInfo slideInfo = null;
		if(slide != null && slide.isFile())
		{
			slideInfo = new SlideInfo();
			slideInfo.setFilePath(slide.getName());
			slideInfo.setIndex(getFileIndex(slideInfo.getFilePath()));
			//slideInfo.setContentType(fileNameMap.getContentTypeFor(slide.getName()));
			if(mimetypesFileTypeMap != null)
			{
				slideInfo.setContentType(mimetypesFileTypeMap.getContentType(slide));
				if(!StringUtilities.isEmpty(slideInfo.getContentType()))
				{
					slideInfo.setFlagImage(slideInfo.getContentType().startsWith(SlideInfo.IMAGE_TYPE));
					slideInfo.setFlagVideo(slideInfo.getContentType().startsWith(SlideInfo.VIDEO_TYPE));
				}
			}
		}
		return slideInfo;
	}
	
	private static int getFileIndex(String fileName){
		int index = 0;
		if(!StringUtilities.isEmpty(fileName)){
			int beginIndex = fileName.lastIndexOf(indexSeperator);
			int endIndex = fileName.lastIndexOf(".");
			String indexStr = fileName.substring((beginIndex+1), endIndex);
			try{
				index = Integer.parseInt(indexStr);
			}
			catch(Exception e){
				index = 0;
			}
		}
		return index;
	}

	//@GET
	@POST
	@Produces("application/json")
	public ArrayList<SlideInfo> getSlidesByCatalogCode(@Context HttpServletRequest request){
		System.out.println(getClass()+" -  getSlidesByCatalogCode");
		String catalog = request.getParameter("catalog");
		return getSlides(catalog);
	}
	
	/*@OPTIONS 
    public Response setHeaders(@Context HttpServletResponse servlerResponse) { 
        servlerResponse.addHeader("Allow-Control-Allow-Methods", "POST,GET,OPTIONS"); 
        servlerResponse.addHeader("Access-Control-Allow-Credentials", "true"); 
        servlerResponse.addHeader("Access-Control-Allow-Origin", "*"); 
        servlerResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With"); 
        servlerResponse.addHeader("Access-Control-Max-Age", "60"); 
        return Response.ok().build(); 
    } */
	
	
	public static void main(String[] args){
		loadSlides();
		System.out.println(" data map "+slideMap);
	}

}
